# -*- coding: utf-8 -*-
# @Time : 2020/9/24 17:21
# @Author : HEAD
# @Email : scg@gmail.com
# @File : mail.py
# @Project : scg_interface
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from common.config import Config, base_path
from common.log import Log

c = Config()
logger = Log.get_logger()


def send_email(report):
    report_file = os.path.join(base_path, c.get_runtime("report_dir"), report)

    # 创建邮件对象
    msg = MIMEMultipart()
    # 配置email头
    msg["Subject"] = c.get_email("subject")
    msg["From"] = c.get_email("user")
    msg["To"] = c.get_email("receiver")
    # 格式化email正文，同时将报告以附件的形式发送
    with open(report_file, "rb") as f:
        body = f.read()
        attach = MIMEApplication(body)
        msg.attach(MIMEText(body, "html", "utf-8"))
        # 给附件重命名，一般和源文件一样
        attach.add_header('Content-Disposition', 'attachment', filename=report)
        msg.attach(attach)

    # 连接smtp服务器,发送邮件
    smtp = smtplib.SMTP()
    smtp.connect(c.get_email("server"))
    smtp.login(c.get_email("user"), c.get_email("pwd"))
    smtp.sendmail(c.get_email("user"), c.get_email("receiver"), msg.as_string())
    logger.debug("邮件发送成功")


if __name__ == "__main__":
    send_email("report.html")
